<?php
namespace app\controller;

use app\BaseController;
use app\model\Spec as SP;
use think\validate\ValidateRule;
use think\facade\Session;
use think\facade\Db;

class Spec extends BaseController
{
    protected $middleware = [
        // 对所有方法有效
        '\app\middleware\NavCheck',
        '\app\middleware\UrlCheck',
        '\app\middleware\LoginCheck',
    ];
    public function index()
    {
        return view();
    }

    public function data($limit,$page)
    {
        $offset = ($page-1)*$limit;
        $list = SP::limit($offset,$limit)->select();
        $count = SP::count();
        return json(["code"=>0,"msg"=>"查询成功","count"=>$count,"data"=>$list]);
    }

    public function add(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $user = new SP;
            $res = $user->save($data);

            if($res) {
                $this->success("添加成功","index");
            }
            $this->error("添加失败");
        }
        return view();
    }

    public function update(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $user = SP::find($data['id']);
            $res = $user->save($data);
            if($res){
                $this->success("修改成功","index");
            }else{
                $this->error("修改失败");
            }
        }

        $id=$this->request->param('id');
        $list = SP::where('id',$id)->find()->getData();
        return view("add",['list'=>$list]);
    }

    public function del(){
        $id = $this->request->param('id');
        $val = Db::table('spec_item')->where('spec_id', $id)->find();
        if(!empty($val)){
            return json(['msg'=>"删除失败,请删除完规格值后,再进行删除",'code'=>400]);
        }
        $res = SP::where('id',$id)->delete();
        if($res){
            return json(['msg'=>"删除成功",'code'=>0]);
        }
        return json(['msg'=>"删除失败",'code'=>400]);

    }


}